package com.lagou.ipersistence.type;

import com.lagou.ipersistence.executor.result.ResultMapException;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Yan Jiahong
 * Created on 2020/11/24
 */
public abstract class BaseTypeHandler<T> implements TypeHandler<T> {
    @Override
    public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            try {
                ps.setNull(i, jdbcType.typeCode);
            } catch (SQLException e) {
                throw new TypeException("当设置空参数时候出错");
            }
        } else {
            try {
                setNonNullParameter(ps, i, parameter, jdbcType);
            } catch (Exception e) {
                throw new TypeException("未第" + i + "位置设非空参数时候出错! 原因: " + e, e);
            }
        }
    }
    
    @Override
    public T getResult(ResultSet rs, String columnName) throws SQLException {
        try {
            return getNonNullResult(rs, columnName);
        } catch (Exception e) {
            throw new ResultMapException("尝试从结果集获取列'" + columnName + "'时候失败. 原因: " + e, e);
        }
    }
    
    public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
    
    public abstract T getNonNullResult(ResultSet rs, String columnName) throws SQLException;
}
